package com.lh.nk;

/**
 * @author: linghao
 * @since: 2023/2/4
 */
public class 判断链表中是否有环NC4 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        node1.next = node2;

        System.out.println(hasCycle(node1));
    }

    // 双指针。快慢指针
    public static boolean hasCycle(ListNode head) {
        if(head == null || head.next == null)return false;
        ListNode f = head;
        ListNode s = head;
        while (f != null && s != null){
            if(f.next != null && f.next.next != null && s.next != null){
                f = f.next.next;
                s = s.next;
                if(f == s)return true;
            }else{
             return false;
            }
        }
        return false;
    }


    static  class ListNode {
         int val;
         ListNode next;
         ListNode(int x) {
             val = x;
             next = null;
         }
     }
}
